from .trait import Trait
from .ttable import ttable
from .girl import Girl
from .girl_template import GirlTemplate

#
# OK, Rather than have the Girl class know how to
# load itself from XML, let's have a loader class
# to do the hard work
#
class UniqueGirlLoader(object):
	def __init__(self, *args, **kw):
		object.__init__(self)
#
#	load is in fact a factory method,
#	creating girl objects and returning them
#
	def load(self, xml_girl):
		girl = Girl()
#
#		now loop over all the dictionary keys
#
		for k in xml_girl.keys():
#
#			get the value using thee XML key
#
			v = xml_girl.get(k)
#
#			convert to our internal key name
#
			k = ttable[k]
#
#			cast non-strings to floats
#
			if k not in [ "name", "desc", "status" ]:
				if v == "":
					v = "0"
				try:
					v = float(v)
				except ValueError:
					s = "error converting field {}, "
					s += "value = '{}'"
					s = s.format(k, v)
					print s
					raise
#
#			set the attribute of the girl object
#
			girl.__dict__[k] = v
		
		girl.arch_name = girl.name

		traits = [t for t in xml_girl if t.tag == "Trait"]
		for t in traits:
			self.load_trait(t, girl)
		
		girl.pics.scan(girl)

		return girl

#
#	and we need to load the trait as well
#
	def load_trait(self, xml_trait, girl):
		name = xml_trait.get("Name")
		girl.add_trait(name)

class GenericGirlLoader(object):
	def __init__(self, *args, **kw):
		object.__init__(self)
#
#	take an xml element from a rgirlsx file and
#	turn it into a template that can be used to generate
#	
#
	def load(self, xml_girl):
		templ = GirlTemplate()
		templ.name = xml_girl.get("Name")
		print ""
		#print "Debug: scanning ", templ.name
		templ.desc = xml_girl.get("Desc")
		templ.human = (xml_girl.get("Human") == "Yes")
		templ.catacomb = (xml_girl.get("Catacomb") == "Yes")
		self.templ = templ
#
#		OK, let's partition the sub-elements
#
		gold = [ el for el in xml_girl if el.tag == "Gold" ][0]
		stats = [ el for el in xml_girl if el.tag == "Stat" ]
		skills = [ el for el in xml_girl if el.tag == "Skill" ]
#
#		do the gold
#
		self.load_gold(gold)
#
#		loop over the stats
#
		for stat in stats:
			self.load_stat(stat)
#
#		skills have the same format, so we can use the
#		same code - for now at least
#
		for skill in skills:
			self.load_stat(skill)
#
#		traits are different, though
#
		traits = [ el for el in xml_girl if el.tag == "Trait" ]
		for trait in traits:
			self.load_trait(trait)
		return templ
	def load_trait(self, xml):
		print "Traits: tag = ", xml.tag
		name = xml.get("Name")
		print "	name = ", name
		pc = xml.get("Percent")
		print "	pc = ", pc
		self.templ.add_trait(name, pc)
	def load_stat(self, xml):
		name = ttable[xml.get("Name")]
		min = xml.get("Min")
		max = xml.get("Max")
		self.templ.add_stat(name, min, max)
	def load_gold(self, xml):
		name = "gold"
		lo = int(xml.get("Min"))
		hi = int(xml.get("Max"))
		self.templ.add_stat("gold", lo, hi)

